package best.driver.android.Utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.*;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.view.*;
import android.view.View.MeasureSpec;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import best.driver.android.BestApp;
import com.nostra13.universalimageloader.utils.L;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Pattern;

public class Utils {

    public static boolean sDebug = true;
    static MediaPlayer sMediaPlayer;

    public static void setRating(RatingBar ratingBar, float level) {
        int min = (int) level;
        if (min != level) { // 带小数的一律按照半星处理
            ratingBar.setRating(min + 0.5f);
        } else {
            ratingBar.setRating(level);
        }
    }

    public static Bitmap convertViewToBitmap(View view) {
        if (view == null) {
            return null;
        }
        view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);

        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();

        return bitmap;
    }

    /**
     * get the width of the device screen
     * 
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * get the height of the device screen
     * 
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 从view 得到图片
     * 
     * @param view
     * @return
     */
    public static Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(MeasureSpec.makeMeasureSpec(0,
                MeasureSpec.UNSPECIFIED), MeasureSpec
                .makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache(true);
        return bitmap;
    }

    /**
     * 排序
     */
    @SuppressWarnings("deprecation")
    public static String toSort(Hashtable<String, String> values) {
        StringBuilder buffer = new StringBuilder();
        ArrayList<String> keys = new ArrayList<String>(values.keySet());
        Collections.sort(keys);

        for (int i = 0, as = keys.size(); i < as; i++) {
            String key = keys.get(i);
            buffer.append(key).append("=")
                    .append(URLEncoder.encode(values.get(key))).append("&");
        }
        return buffer.toString().substring(0, buffer.length() - 1);
    }

    public static byte[] readBtyeStream(InputStream oInputStream, int length)
            throws Exception {
        if (oInputStream != null) {
            int bufferSize = 1024;
            if (length > 0) {
                bufferSize = length;
            }
            ByteArrayOutputStream oBos = new ByteArrayOutputStream();
            int wMid = 0;
            byte[] bzBuf = new byte[bufferSize];
            while ((wMid = oInputStream.read(bzBuf, 0, bufferSize)) != -1) {
                oBos.write(bzBuf, 0, wMid);
            }
            oBos.flush();
            byte[] data = oBos.toByteArray();
            oBos.close();
            return data;
        }
        return null;
    }

    /** 排序 并 MD5 */
    public static String toSortMD5(Hashtable<String, String> values) {
        StringBuilder buffer = new StringBuilder();
        ArrayList<String> keys = new ArrayList<String>(values.keySet());
        Collections.sort(keys);

        for (int i = 0, as = keys.size(); i < as; i++) {
            String key = keys.get(i);
            buffer.append(key).append(values.get(key));
        }
        buffer.append("47f3db98-eaa5-11e1-92bc-00163e0107dd"); // 盐
        return MD5.md5(buffer.toString());
    }

    public static String getJsonText(JSONObject obj, String tag) {
        if (obj == null || tag == null) {
            return "";
        }
        try {
            return obj.getString(tag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getJsonTextZH(JSONObject obj, String tag) {
        if (obj == null || tag == null) {
            return "";
        }
        try {
            return obj.getJSONObject(tag).getString("zh");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 读取Assets中的文件
     * 
     * @param context
     * @param NAME
     * @return
     */
    public static String readAssetsFile(Context context, String NAME) {
        BufferedReader bReader = null;
        InputStream in = null;
        try {
            AssetManager assetManager = context.getAssets();
            in = assetManager.open(NAME);
            bReader = new BufferedReader(new InputStreamReader(in));
            String line = null;
            StringBuilder buffer = new StringBuilder();
            while ((line = bReader.readLine()) != null) {
                buffer.append(line);
                buffer.append("\n");
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bReader != null) {
                try {
                    bReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public static <T> List<T> subList(List<T> sourceList, int start, int len) {
        int size = sourceList.size();
        List<T> result = new ArrayList<T>();
        for (int i = start; i < start + len; ++i) {
            if (i >= size)
                break;
            result.add(sourceList.get(i));
        }
        return result;
    }

    /**
     * 隐藏软键盘
     * 
     * @param context
     */
    public static void hideKeyboard(Activity context) {
        try {
            InputMethodManager localInputMethodManager = (InputMethodManager) context
                    .getSystemService(Context.INPUT_METHOD_SERVICE);

            View currentFocus = context.getCurrentFocus();
            if (currentFocus != null) {
                IBinder localIBinder = currentFocus.getWindowToken();
                if (localIBinder != null) {
                    localInputMethodManager
                            .hideSoftInputFromWindow(localIBinder, 0);
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 显示软键盘
     * 
     * @param context
     * @param edit
     */
    public static void showKeyboard(Context context, EditText edit) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(edit, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    public static boolean isTaskRunningForebackgound(Context context) {
        ActivityManager manager = (ActivityManager) context
                .getSystemService(Activity.ACTIVITY_SERVICE);
        List<RunningTaskInfo> taskList = manager.getRunningTasks(1);
        if (taskList == null || taskList.isEmpty()) {
            return false;
        }
        RunningTaskInfo taskInfo = taskList.get(0);
        ComponentName componentName = taskInfo.topActivity;
        if (context.getPackageName().equals(componentName.getPackageName())) {
            return true;
        }
        return false;
    }

    /**
     * 字符串连接
     * 
     * @param strs
     * @return
     */
    public static String linkString(String... strs) {
        StringBuffer stringBuffer = new StringBuffer();
        for (String str : strs) {
            stringBuffer.append(str);
        }
        return stringBuffer.toString();
    }

    /**
     * 去除小数
     * 
     * @param decimalStr
     * @return
     */
    public static String removeDecimalStr(String decimalStr) {
        if (decimalStr == null)
            return "";
        return decimalStr.indexOf(".") > 0 ? decimalStr.split("\\.")[0]
                : decimalStr;
    }

    /**
     * 截取日期，2014-02-02 02:02:02 ==> 2014-02-02
     * 
     * @param datetimeStr
     * @param subLength
     * @return
     */
    public static String subDatetimeStr(String datetimeStr) {
        if (datetimeStr == null)
            return "";
        return datetimeStr.length() >= 10 ? datetimeStr.substring(0, 10)
                : datetimeStr;
    }

    /**
     * 截取日期，2014-02-02 02:02:02 ==> 2014-02-02 02:02
     * 
     */
    public static String subDatetimeStrToMinute(String datetimeStr) {
        if (datetimeStr == null)
            return "";
        return datetimeStr.length() >= 16 ? datetimeStr.substring(0, 16)
                : datetimeStr;
    }

    public static Bitmap convertHeadPicture(Bitmap bitmap) {

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        Bitmap output = Bitmap.createBitmap(w, w, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();

        int y = (h - w) / 2 - 8;
        if (y < 0) {
            y = 0;
        }
        final Rect srcRect = new Rect(0, y, w, y + w);
        final Rect destRect = new Rect(0, 0, w, w);
        final RectF destRectF = new RectF(destRect);
        final float roundPx = w / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(destRectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, srcRect, destRect, paint);

        return output;
    }

    public static boolean checkIsPhone(String phone) {
        return Pattern.matches("^\\d{10,11}$", phone);
    }

    public static boolean isXiaoMi() {
        return "xiaomi".equalsIgnoreCase(Build.MANUFACTURER.toLowerCase());
    }

    public static void setFullScreen(Activity activity, boolean isFullScreen) {
        int v = isFullScreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN
                : WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN;

        activity.getWindow().setFlags(v, v);
        activity.getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR,
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR);
    }

    public static boolean appIsInTheBackground() {

        KeyguardManager mKeyguardManager = (KeyguardManager) BestApp
                .getInstance().getSystemService(Context.KEYGUARD_SERVICE);

        if (mKeyguardManager.inKeyguardRestrictedInputMode()) {
            return true;
        }

        ActivityManager manager = (ActivityManager) BestApp.getInstance()
                .getSystemService(Activity.ACTIVITY_SERVICE);
        List<RunningTaskInfo> taskList = manager.getRunningTasks(1);
        if (taskList != null && taskList.size() > 0) {
            RunningTaskInfo taskInfo = taskList.get(0);
            ComponentName componentName = taskInfo.topActivity;
            if (BestApp.getInstance().getPackageName()
                    .equals(componentName.getPackageName())) {
                return false;
            }
        }
        return true;
    }

    public static void launchApp() {
        Intent intent = createLaunchAppIntent();
        BestApp.getInstance().startActivity(intent);
    }

    public static Intent createLaunchAppIntent() {

        Intent intent = new Intent();
        Activity activity = BestApp.getInstance().getLastActivity();

        if (activity != null) {
            intent.setClass(BestApp.getInstance(), activity.getClass());
        } else {
            //intent.setClass(BestApp.getInstance(), MenuFragment.class);
        }

        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        return intent;

    }

    @SuppressWarnings("unchecked")
    public static <T> T cloneTo(T src) throws RuntimeException {
        ByteArrayOutputStream memoryBuffer = new ByteArrayOutputStream();
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        T dist = null;
        try {
            out = new ObjectOutputStream(memoryBuffer);
            out.writeObject(src);
            out.flush();
            in = new ObjectInputStream(new ByteArrayInputStream(
                    memoryBuffer.toByteArray()));
            dist = (T) in.readObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (out != null)
                try {
                    out.close();
                    out = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            if (in != null)
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
        }
        return dist;
    }

    // 判断网络是否联通
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    // 判断网络是否联通
    public static boolean isWifiConnected() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) BestApp
                .getInstance().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null && mNetworkInfo.isAvailable()
                && mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    // bookingid 转化为notifyid 作为个推的唯一标识

    public static int createNotifyIdByBookingId(String bookingId) {
        Logger.d("PUSH", "bookingid hashcode =" + bookingId.hashCode());
        return bookingId.hashCode();
    }

    /**
     * 按照弃尾法处理比较大的数字
     * 
     * @param balance
     * @return
     */
    public static String getNumberByplicy(String balance) {
        Float parseFloat = Float.parseFloat(balance);
        String outMoney;
        if (parseFloat <= 10000) {
            outMoney = new BigDecimal(parseFloat).setScale(0,
                    BigDecimal.ROUND_DOWN) + "";
        } else if (parseFloat > 10000 & parseFloat <= 100000) {
            outMoney = new BigDecimal(parseFloat / 10000).setScale(1,
                    BigDecimal.ROUND_DOWN) + "万";
        } else {
            outMoney = new BigDecimal(parseFloat / 10000).setScale(0,
                    BigDecimal.ROUND_DOWN) + "万";
        }
        if(outMoney.endsWith(".0")) {
            outMoney =  outMoney.substring(0, outMoney.length()-2) ;
        }
        return outMoney;
    }

    public static String getNormalPrice(String  price) {
       return getNormalPrice(Long.valueOf(price));
    }

    public static String getNormalPrice(long price) {
        return DecimalFormat.getNumberInstance().format(price);
    }

    public static void playNotification(boolean loop) {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(BestApp.getInstance().getApplicationContext(), notification);
        r.play();
        //return playSystemSound(RingtoneManager.TYPE_NOTIFICATION, loop);
    }

    private static boolean playSystemSound(int type, boolean loop) {

        Uri uri = Settings.System.DEFAULT_NOTIFICATION_URI;
        final int streamType = RingtoneManager.TYPE_NOTIFICATION;

        return playSound(streamType, uri, loop);
    }

    private static boolean playSound(final int streamType, final Uri uri, Boolean loop) {
        try {
            L.d("playSound.1 try to play sound:%s", uri);
            if (uri == null) {
                return false;
            }

            if (sMediaPlayer != null) {
                try {
                    if (sMediaPlayer.isPlaying()) {
                        sMediaPlayer.stop();
                    }
                } catch (Exception e) {
                    L.d("playSound.2 e:%s", e.toString());
                    e.printStackTrace();
                }

                try {
                    sMediaPlayer.release();
                    sMediaPlayer = null;
                } catch (Exception e) {
                    L.d("playSound.3 e:%s", e.toString());
                    e.printStackTrace();
                }
            }

            sMediaPlayer = new MediaPlayer();
            final AudioManager audioManager = (AudioManager) BestApp.getInstance()
                    .getSystemService(Context.AUDIO_SERVICE);
            final int volume = audioManager.getStreamVolume(streamType);
            L.d("playSound.4 save audio vol = " + volume);


            sMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                    sMediaPlayer = null;
                    audioManager.setStreamVolume(streamType, volume, 0);
                }
            });
            sMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mp.release();
                    sMediaPlayer = null;
                    L.e("playSound.5 Error in MediaPlayer: (" + what
                            + ") with extra (" + extra + ")");
                    audioManager.setStreamVolume(streamType, volume, 0);
                    return false;
                }
            });
            sMediaPlayer.setAudioStreamType(streamType);
            sMediaPlayer.setLooping(loop);
            try {
                sMediaPlayer.setDataSource(BestApp.getInstance(), uri);
            } catch (Exception e) {
                L.d("playSound.6 e:%s", e.toString());
                e.printStackTrace();
            }
            try {
                sMediaPlayer.prepare();
            } catch (Exception e) {
                L.d("playSound.7 e:%s", e.toString());
                e.printStackTrace();
            }
            sMediaPlayer.start();
            return true;
        } catch (IllegalStateException e) {
            L.d("playSound.8 e:%s", e.toString());
            e.printStackTrace();
        }
        return false;
    }

    public static boolean isNameAdressFormat(String email) {
        return email.matches("^[\\.a-zA-Z0-9_\\-]+@[\\.a-zA-Z0-9_\\-]+(\\.[a-zA-Z0-9_\\-]+)+$");
    }


}
